<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="medium" :inline="true" label-width="68px">
      <el-form-item label="所在周" prop="week">
        <el-date-picker
          :clearable="false"
          v-model="queryParams.date"
          type="week"
          size="large"
          format="yyyy 第 WW 周"
          placeholder="选择周">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="large" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="large" @click="resetQuery">重置</el-button>
      </el-form-item>
      <el-form-item style="float: right">
        <el-button type="primary" icon="el-icon-search" size="large" @click="handleSave">保存</el-button>
      </el-form-item>
    </el-form>
    <table class="course-table">
      <thead>
        <tr>
          <th>时间</th>
          <th>周一</th>
          <th>周二</th>
          <th>周三</th>
          <th>周四</th>
          <th>周五</th>
          <th>周六</th>
          <th>周日</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(course, index) in courseData" :key="index">
          <td>{{ course.time }}</td>
          <td
  v-for="(day, dayIndex) in ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']"
  :key="dayIndex"
  @click="toggleCellSelection(index, day)"
  :class="{'selected-cell': isCellSelected(index, day)}"
>
  <div v-if="course[day]" class="course-cell">
    <div class="course-name">{{ course[day].courseName }}</div>
    <div class="course-teacher">{{ course[day].teacherName }}</div>
    <div class="course-location">{{ course[day].location }}</div>
  </div>
</td>
        </tr>
      </tbody>
    </table>
    <el-dialog title="选择课程" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="课程" prop="courseId">
          <el-select v-model="form.courseId" placeholder="请选择课程">
            <el-option
              v-for="dict in this.courseOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上课地点" prop="location">
          <el-input v-model="form.location" placeholder="请填写上课地点" style="width: 216px"></el-input>
        </el-form-item>
        <el-form-item label="课程结束时间" prop="endWeek">
          <el-date-picker
            :clearable="false"
            v-model="form.endWeek"
            type="week"
            size="large"
            format="yyyy 第 WW 周"
            :picker-options="pickerOptions"
            placeholder="选择周">
          </el-date-picker>
          <el-tooltip class="item" effect="dark" content="填写该字段将自动保存当前周到结束周的相同时间段的课程安排" placement="right">
            <i class="el-icon-warning-outline"/>
          </el-tooltip>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import moment from 'moment'
import {getSchedule,addSchedule} from '@/api/ysg/course'
import {getCourseOptions} from '@/api/ysg/common'
const defaultData = [
  {
    time: '09:00-10:30',
  },
  {
    time: '10:30-12:00',
  },
  {
    time: '13:30-15:00',

  },
  {
    time: '15:00-16:30',

  },
  {
    time: '16:30-18:00',

  },
  {
    time: '18:00-19:30',
  }
]
export default {
  name: 'CourseSchedule',
  data() {
    return {
      classId:null,
      queryParams:{
        date:null,
        week:null,
        year:null,
      },
      form:{},
      open:false,
      courseData: [],
      selectedCells: new Set(), // 使用Set存储选中的单元格key
      rules: {
        courseId: [
          {required: true, message: "所选课程不能为空", trigger: "blur"}
        ],
        location: [
          {required: true, message: "上课地点不能为空", trigger: "blur"}
        ],
      },
      courseOptions:[],
      pickerOptions:{
        disabledDate:(time) => !moment(time).isAfter(this.queryParams.date)
      }
    }
  },
  created() {
    this.classId = this.$route.params && this.$route.params.classId
    this.queryParams.classId = this.classId;
    const dateStr = new moment().format('YYYY-WW')
    this.queryParams.year = dateStr.split('-')[0]
    this.queryParams.week = dateStr.split('-')[1]
    this.queryParams.date = new moment()
  },
  mounted() {
    this.getSchedule()
    this.getOptions()
  },
  methods: {
    getSchedule() {
      this.selectedCells.clear()
      const param = {}
      param.classId = this.classId
      param.year = this.queryParams.year
      param.week = this.queryParams.week
      getSchedule(param).then(res => {
        if(res.data.length > 0){
          this.courseData = res.data
        }else {
          this.courseData = defaultData
        }
      })

    },
    getOptions() {
      getCourseOptions({ classId: this.classId }).then(res => {
        this.courseOptions = res.data
      })
    },
    handleSave() {
      if(this.selectedCells.size === 0) {
        this.$modal.msgWarning("请至少选择一个需要设置的时间段")
        return
      }
      this.open = true
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          console.log(this.form.endWeek);
          const schedules = []
          this.selectedCells.forEach(key => {
            const [rowIndex, day] = key.split('-');
            if(!this.form.endWeek) {
              schedules.push({courseId: this.form.courseId,
                sort:parseInt(rowIndex) + 1,
                year:this.queryParams.year,
                week:this.queryParams.week,
                day:day,
                classId:this.classId,
                location:this.form.location,
              })
            }else {
              let date = moment(this.queryParams.date)
              while (date.isBefore(moment(this.form.endWeek).add(1,"week"))) {
                schedules.push({courseId: this.form.courseId,
                  sort:parseInt(rowIndex) + 1,
                  year: date.format("YYYY"),
                  week: date.format("WW"),
                  day:day,
                  classId:this.classId,
                  location:this.form.location,
                })
                date.add(1,"week")
              }
            }
          });
          console.log(schedules)
          addSchedule(JSON.stringify(schedules)).then(res => {
            this.$modal.msgSuccess("保存成功")
            this.getSchedule()
            this.$refs.form.resetFields()
            this.open = false
          })
        }
      })
    },
    cancel() {
      this.$refs.form.resetFields()
      this.open = false
    },
    handleQuery () {
      const dateStr = moment(this.queryParams.date).format('YYYY-WW')
      this.queryParams.year = dateStr.split('-')[0]
      this.queryParams.week = dateStr.split('-')[1]
      this.getSchedule()
    },
    resetQuery() {
      this.$refs.queryForm.resetFields()
      this.queryParams.date = new moment()
      const dateStr = new moment().format('YYYY-WW')
      this.queryParams.year = dateStr.split('-')[0]
      this.queryParams.week = dateStr.split('-')[1]
      this.getSchedule()
    },
    toggleCellSelection(rowIndex, day) {
        const course = this.courseData[rowIndex][day];
    if (course && course.courseName) {
      this.$modal.msgWarning('该时间段已有课程安排，不可选择');
      return;
    }
    const key = `${rowIndex}-${day}`;
    if (this.selectedCells.has(key)) {
      this.selectedCells.delete(key);
    } else {
      this.selectedCells.add(key);
    }
    this.$forceUpdate();
  },
  isCellSelected(rowIndex, day) {
    return this.selectedCells.has(`${rowIndex}-${day}`);
  },
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.course-table {
  width: 100%;
  table-layout: fixed;  /* 添加固定布局 */
  border-collapse: collapse;
  font-size: 16px;
}
.course-table th, .course-table td {
  border: 1px solid #ebeef5;
  padding: 12px;
  text-align: center;
  height: 120px;
  vertical-align: middle;
  word-break: break-word;  /* 添加自动换行 */
}
.course-table th:nth-child(1),
.course-table td:nth-child(1) {  /* 修改第一列样式 */
  background-color: #46a6ff;
  color: #fff;
  font-size: 24px;
}
.course-table td:nth-child(1):hover {  /* 取消第一列hover效果 */
  background-color: #46a6ff !important;
}
.course-table th:nth-child(2),
.course-table th:nth-child(3),
.course-table th:nth-child(4),
.course-table th:nth-child(5),
.course-table th:nth-child(6),
.course-table th:nth-child(7),
.course-table th:nth-child(8) { width: calc((100% - 120px) / 7); }  /* 其他列平均分配剩余宽度 */
.course-table th {
  background-color: #46a6ff;
  color: #fff;
  font-size: 24px;
}
.course-table tr:nth-child(even) {
  background: rgba(70, 166, 255, 0.06);
}
.course-table td:hover {
  background-color: #f5f7fa;
}
.course-cell {
  display: flex;
  flex-direction: column;
  justify-content: center;
  height: 100%;
}
.course-name {
  font-weight: bold;
  margin-bottom: 5px;
}
.course-teacher {
  color: #666;
  margin-bottom: 5px;
}
.course-location {
  color: #46a6ff;
}
.selected-cell {
  background-color: #e6f7ff !important;
  box-shadow: inset 0 0 0 2px #46a6ff;
}
</style>

